package org.idea.ietty.core;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.idea.ietty.common.constants.IettyConstants;
import org.idea.ietty.container.ClassPathXmlApplicationContext;
import org.idea.ietty.container.IettyApplicationContext;

import java.net.InetSocketAddress;

import static org.idea.ietty.common.constants.IettyConstants.IettyStartStatusEnum.HTTP_SERVER;
import static org.idea.ietty.common.constants.IettyConstants.IettyStartStatusEnum.STATIC_SERVER;

/**
 * 基于netty编写的一个http服务器
 *
 * @Author idea
 * @Date created in 9:56 下午 2020/5/2
 */
public class IettyHttpServer {

    private int port;

    private String xmlPath;

    private Integer serverStatusCode;

    private static IettyApplicationContext iettyApplicationContext;

    public IettyHttpServer(int port) {
        this.port = port;
    }

    public IettyHttpServer(int port,String xmlPath){
        this.port=port;
        this.xmlPath=xmlPath;
    }

    public void start() throws Exception {
        long begin = System.currentTimeMillis();
        if(this.xmlPath==null){
            this.serverStatusCode= STATIC_SERVER.getCode();
        }else{
            // 开始加载容器里面的bean
            iettyApplicationContext = new ClassPathXmlApplicationContext(xmlPath);
            this.serverStatusCode= HTTP_SERVER.getCode();
        }

        ServerBootstrap bootstrap = new ServerBootstrap();
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup work = new NioEventLoopGroup();
        bootstrap.group(boss, work)
                .handler(new LoggingHandler(LogLevel.DEBUG))
                .channel(NioServerSocketChannel.class)
                .childHandler(new HttpServerInitializer(iettyApplicationContext));
        ChannelFuture f = bootstrap.bind(new InetSocketAddress(port)).sync();

        long end = System.currentTimeMillis();
        System.out.println("===================== ietty-server is start success ===================== ");
        System.out.println("===================== consuming time is  " + (end - begin) + " millSecond ===================== ");
        System.out.println("========================================================================= ");
        f.channel().closeFuture().sync();
    }

}
